/*
 * Copyright (c) 2014-2016 Alibaba Group. All rights reserved.
 * License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include "FreeRTOS.h"


#include "iot_import.h"
#ifdef DEBUG
    #define PLATFORM_OS_PERROR(format, ...) HAL_Printf( "[OS]%u %s " format "\r\n", __LINE__, __FUNCTION__, ##__VA_ARGS__)
    #define PLATFORM_OS_PDEBUG(format, ...) HAL_Printf( "[OS]%s " format "\r\n", __FUNCTION__, ##__VA_ARGS__)
#else
    #define PLATFORM_OS_PERROR(format, ...)
    #define PLATFORM_OS_PDEBUG(format, ...)
#endif

void *HAL_MutexCreate(void)
{
	//xSemaphoreCreateMutex
    return (void*)1;
}

void HAL_MutexDestroy(_IN_ void *mutex)
{
    return;
}

void HAL_MutexLock(_IN_ void *mutex)
{
    return;
}

void HAL_MutexUnlock(_IN_ void *mutex)
{
	//xSemaphoreGive(*mutex);

    return;
}

void *HAL_Malloc(_IN_ uint32_t size)
{
    void* ptr = malloc(size);
    PLATFORM_OS_PDEBUG("%#x,%d bytes", ptr, size);
    return ptr;
}

void HAL_Free(_IN_ void *ptr)
{
    PLATFORM_OS_PDEBUG("%#X.", ptr);
    free(ptr);
    return;
}

uint64_t HAL_UptimeMs(void)
{
    uint32_t time_ms;
    time_ms = xTaskGetTickCount();
    return time_ms;
}

void HAL_SleepMs(_IN_ uint32_t ms)
{
    vTaskDelay(ms);
}

void HAL_Srandom(uint32_t seed)
{
    srand(seed);
}

uint32_t HAL_Random(uint32_t region)
{
    return (region > 0) ? (rand() % region) : 0;
}

int HAL_Snprintf(_IN_ char *str, const int len, const char *fmt, ...)
{
    va_list args;
    int     rc;

    va_start(args, fmt);
    rc = vsnprintf(str, len, fmt, args);
    va_end(args);

    return rc;
}

int HAL_Vsnprintf(_IN_ char *str, _IN_ const int len, _IN_ const char *format, va_list ap)
{
    return vsnprintf(str, len, format, ap);
}

void HAL_Printf(_IN_ const char *fmt, ...)
{
    va_list args;

    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);

    fflush(stdout);
}

int HAL_GetPartnerID(char pid_str[PID_STRLEN_MAX])
{
    memset(pid_str, 0x0, PID_STRLEN_MAX);
#ifdef __UBUNTU_SDK_DEMO__
    strcpy(pid_str, "example.demo.partner-id");
#endif
    return strlen(pid_str);
}

int HAL_GetModuleID(char mid_str[MID_STRLEN_MAX])
{
    memset(mid_str, 0x0, MID_STRLEN_MAX);
#ifdef __UBUNTU_SDK_DEMO__
    strcpy(mid_str, "example.demo.module-id");
#endif
    return strlen(mid_str);
}

